<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, unref } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import car from "./car.json";

withDefaults(
  defineProps<{
    width?: string;
    height?: string;
  }>(),
  {
    width: "100%",
    height: "98%",
  }
);

(window as any)._AMapSecurityConfig = {
  securityJsCode: "b68e770e5357e61bc663f74fee917dca",
};
// 全局AMapUI变量
const wrapRef = ref<HTMLDivElement | null>(null);
const district = ref(); // 区域掩模
const loca = ref(); // 区域掩模
const map = ref(); // 地图
const mapBoundsCenter = ref(); // 区域中心
const mapBoundsCenterLevel = ref(); // 区域中心
// const emits = defineEmits(['handleOpen', 'handleClose']);
const CQ_POINT = [106.588134, 29.567803]; // 目标坐标
const DESTINATION_POINT = [107.075301, 29.852268]; // 目标坐标
const dataPoints = computed(() => {
  let tempData = car.map((item: any) => {
    let co = item.center.split(",").map((item: any) => Number(item)); // 将字符串拆分成坐标数组数据
    return {
      type: "Feature",
      properties: { province: item.name },
      geometry: {
        type: "Point", // 点位
        coordinates: co,
      },
    };
  });
  return {
    type: "FeatureCollection",
    features: tempData,
  };
});
const dataLines = computed(() => {
  let tempData = car.map((item) => {
    let co = item.center.split(",").map((item) => Number(item)); // 将字符串拆分成坐标数组数据
    return {
      type: "Feature",
      properties: { province: item.name },
      geometry: {
        type: "LineString", // 线段
        coordinates: [
          CQ_POINT, // target location
          co,
        ],
      },
    };
  });
  return {
    type: "FeatureCollection",
    features: tempData,
  };
});
const dataLinesReverse = computed(() => {
  let tempData = car.map((item) => {
    let co = item.center.split(",").map((item) => Number(item));
    return {
      type: "Feature",
      properties: { province: item.name },
      geometry: {
        type: "LineString", // 线段
        coordinates: [
          co,
          CQ_POINT, // target location
        ],
      },
    };
  });
  return {
    type: "FeatureCollection",
    features: tempData,
  };
});
const initMap = async () => {
  AMapLoader.load({
    key: "6d055920a47dac2b9b565027bc36e5ab", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    AMapUI: {
      version: "1.1",
      plugins: ["geo/DistrictExplorer"],
    },
    Loca: {
      version: "2.0",
    },
    plugins: ["AMap.Loca", "AMap.DistrictSearch"], // 需要使用的的插件列表
  })
    .then((AMap) => {
      district.value = new AMap.DistrictSearch({
        subdistrict: 0,
        extensions: "all",
      });

      oneMapDistrictExplorer(AMap);

      mapBoundsCenterLevel.value = 7;
    })
    .catch((e) => {
      console.log(e);
    });
};
// 单个区域
const oneMapDistrictExplorer = (AMap: any) => {
  const wrapEl = unref(wrapRef);
  district.value.search("500000", (status: any, result: any) => {
    let status1 = status;
    status1;
    const bounds = result.districtList[0].boundaries;
    let bounds_center = result.districtList[0].center;
    mapBoundsCenter.value = bounds_center;
    const mask: any = [];
    for (let i = 0; i < bounds.length; i++) {
      mask.push([bounds[i]]);
    }
    map.value = new AMap.Map(wrapEl, {
      // 设置地图容器id
      mask: mask, // 为Map实例制定掩模的路径,各图层将值显示路径范围内图像,3D模式下有效
      zoom: 8, // 设置当前显示级别
      expandZoomRange: true, // 开启显示范围设置
      zooms: [4, 20], //最小显示级别为7，最大显示级别为20
      center: [bounds_center.lng + 1, bounds_center.lat], // 设置地图中心点位置
      viewMode: "3D", // 特别注意,设置为3D则其他地区不显示
      zoomEnable: true, // 是否可以缩放地图
      resizeEnable: true,
      mapStyle: "amap://styles/grey",
      // mapStyle: 'amap://styles/9e38c523c5eae28c8b2d0431bf320928'
    });
    getLocal(AMap);
    let polyArr: any = [];
    for (let i = 0; i < bounds.length; i++) {
      polyArr.push(bounds[i]);
    }
    const polyline = new AMap.Polyline({
      path: polyArr, // polyline 路径，支持 lineString 和 MultiLineString
      strokeColor: "#ace6f9", // 线条颜色，使用16进制颜色代码赋值。默认值为#00D3FC
      strokeWeight: 3, // 轮廓线宽度,默认为:2
      strokeOpacity: 1,
      strokeStyle: "solid",
    });
    polyline.setMap(map.value);
  });
};
const getLocal = (AMap: any) => {
  // 文字图层
  let labelLayer = new AMap.LabelsLayer({
    rejectMapMask: true,
    collision: true,
    animation: true,
  });
  map.value.add(labelLayer);

  loca.value = new Loca.Container({
    map: map.value,
  });

  let scatterLayer2 = new Loca.ScatterLayer({
    zIndex: 10,
    opacity: 0.8,
    visible: true,
    zooms: [2, 22],
  });
  let scatterLayer3 = new Loca.ScatterLayer({
    zIndex: 10,
    opacity: 0.8,
    visible: true,
    zooms: [2, 22],
  });

  let centerPoint = new Loca.GeoJSONSource({
    data: {
      type: "FeatureCollection",
      features: [
        {
          type: "Feature",
          geometry: {
            type: "Point",
            coordinates: CQ_POINT,
          },
        },
      ],
    },
  });
  scatterLayer3.setSource(centerPoint);
  scatterLayer3.setStyle({
    size: [30000, 30000],
    unit: "meter",
    texture: "https://a.amap.com/Loca/static/static/center-point.png",
  });
  loca.value.add(scatterLayer3);

  let setLabelsLayer = (data: any) => {
    labelLayer.clear();
    data.features.forEach((item: any) => {
      let labelsMarker = new AMap.LabelMarker({
        name: item.properties.province,
        position: item.geometry.coordinates,
        zooms: [2, 22],
        opacity: 1,
        zIndex: 10,
        text: {
          content: item.properties.province,
          direction: "bottom",
          offset: [0, -5],
          style: {
            fontSize: 13,
            fontWeight: "normal",
            fillColor: "#fff",
          },
        },
      });
      labelLayer.add(labelsMarker);
    });
    labelLayer.add(
      new AMap.LabelMarker({
        name: "重庆",
        position: CQ_POINT,
        zooms: [2, 22],
        opacity: 1,
        zIndex: 10,
        rank: 100,
        text: {
          content: "重庆",
          direction: "bottom",
          offset: [0, -5],
          style: {
            fontSize: 13,
            fontWeight: "normal",
            fillColor: "#fff",
          },
        },
      })
    );
  };

  const geoDataPoints = new Loca.GeoJSONSource({
    data: dataPoints.value,
  });
  const geoDataLines = new Loca.GeoJSONSource({
    data: dataLines.value,
  });
  const geoDataLinesReverse = new Loca.GeoJSONSource({
    data: dataLinesReverse.value,
  });

  let loadLocation = () => {
    setLabelsLayer(dataPoints.value);
    scatterLayer2.setSource(geoDataPoints);
    scatterLayer2.setStyle({
      size: [55000, 55000],
      unit: "miter",
      animate: true,
      duration: 1000,
      texture: "https://a.amap.com/Loca/static/static/orange.png",
      // texture: 'https://a.amap.com/Loca/static/static/green.png',
    });
    loca.value.add(scatterLayer2);

    // this.loca.animate.start() // 开始动画
  };
  loadLocation();

  let linkLayer = new Loca.LinkLayer({
    zIndex: 20,
    opacity: 1,
    visible: true,
    zooms: [2, 22],
  });
  let loadLine = () => {
    linkLayer.setSource(geoDataLines);
    linkLayer.setStyle({
      lineColors: ["#ff7514", "#ff0008"],
      height: (index: any, item: any) => {
        return item.distance / 2;
      },
      smoothSteps: 300,
    });
    loca.value.add(linkLayer);
  };
  loadLine()

  // pulse layer
  // 
  let pulseLayer = new Loca.PulseLinkLayer({
    zIndex: 20,
    opacity: 1,
    visible: true,
    zooms: [2, 22],
  });
  let loadPulse = () => {
    pulseLayer.setSource(geoDataLinesReverse);
    pulseLayer.setStyle({
      height: (index: any, item: any) => {
        index
        return item.distance / 2;
      },
      unit: "meter",
      dash: [40000, 0, 40000, 0],
      lineWidth: function () {
        return [10000, 1000]; // 始末 节点的线段宽度
      },
      // altitude: 1000,
      smoothSteps: 100, // 曲线圆滑度
      speed: function () {
        return 1000 + Math.random() * 200000;
      },
      flowLength: 100000,
      lineColors: function () {
        return ["rgb(255,221,0)", "rgb(255,141,27)", "rgb(65,0,255)"];
      },
      maxHeightScale: 0.3, // 弧顶位置比例
      headColor: "rgba(255, 255, 0, 1)",
      trailColor: "rgb(255,84,84)",
    });
    loca.value.add(pulseLayer);
  };
  loadPulse();

  map.value.on("complete", () => {
    loca.value.animate.start();
  });
};



onMounted(() => {
  initMap();
});
onUnmounted(() => {
  map.value?.destroy();
});
</script>
<template>
  <div ref="wrapRef" class="wrapRef" :style="{ height, width }"></div>
</template>

<style lang="less">
.wrapRef {
  .amap-logo {
    display: none !important;
  }

  .amap-copyright {
    opacity: 0;
  }
}
.wrapRef {
  background-color: transparent !important;
  background-image: none;
}
</style>
